#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
cron: 8 6 * * *
new Env('飞牛论坛签到')
"""
# 功能：飞牛论坛个人签到，可以获取积分，积分暂时不知道有什么用
# 网址：https://club.fnnas.com
# 变量：FN_COOKIE，多个账号需要建多个FN_COOKIE
# 其他：此版本使用cookie
# 脚本日期：2025年9月9日

import re, time, sys, os
import requests

# ---------- 聚合推送配置 ----------
AGGRE_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'dailylog')

IMMEDIATE = False          # True 实时推送，False 汇总推送
def push(title, text=""):
    if IMMEDIATE:
        from notify import send
        send(title, text)
    else:
        with open(AGGRE_FILE, "a", encoding="utf-8") as f:
            f.write(f"{title}\n{text}\n{'-'*40}\n")

SIGN_PAGE = 'https://club.fnnas.com/plugin.php?id=zqlj_sign'
UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36 Edg/140.0.0.0'

# ---------- 工具 ----------
def parse_env():
    raw = os.getenv('FN_COOKIE', '').strip()
    if not raw:
        raise RuntimeError('环境变量 FN_COOKIE 未设置')
    return [c.strip() for c in raw.split('\n') if c.strip()]

def get_stat(txt: str):
    """返回 (sign, status, 统计dict)"""
    # 按钮文字
    st = re.search(r'<a[^>]*class="btna"[^>]*>(.*?)</a>', txt)
    status = st.group(1).strip() if st else ''
    # 8 位 sign
    m = re.search(r'sign=([a-f0-9]{8})', txt)
    sign = m.group(1) if m else None
    # 7 个 <li>
    keys = ['最近打卡', '本月打卡', '连续打卡', '累计打卡',
            '累计奖励', '最近奖励', '当前打卡等级']
    lis = re.findall(r'<li>([^<]+)</li>', txt)
    stat = dict(zip(keys, lis)) if len(lis) >= len(keys) else \
           {k: lis[i] if i < len(lis) else '' for i, k in enumerate(keys)}
    return sign, status, stat

def sign_one(cookie: str):
    sess = requests.Session()
    sess.headers.update({'Cookie': cookie, 'User-Agent': UA})

    # 重试 1 次
    for _ in range(2):
        try:
            resp = sess.get(SIGN_PAGE)
            resp.raise_for_status()
            sign, status, stat = get_stat(resp.text)

            if '已打卡' in status:
                return f"✅今日已打卡\n 😀 {stat['本月打卡']} \n ♂️ {stat['连续打卡']} \n 🚚{stat['累计打卡']}\n 💾{stat['累计奖励']} \n ✋🏼{stat['当前打卡等级']}"

            if not sign:
                return '提取 sign 失败'

            # 真正打卡
            url = f'{SIGN_PAGE}&sign={sign}'
            resp2 = sess.get(url)
            resp2.raise_for_status()
            if '恭喜您，打卡成功！' in resp2.text:
                return f"✅打卡成功\n 😀 {stat['本月打卡']} \n ♂️ {stat['连续打卡']} \n 🚚{stat['累计打卡']}\n 💾{stat['累计奖励']} \n ✋🏼{stat['当前打卡等级']}"
            return '打卡失败（未知）'
        except Exception as e:
            last_e = e
            time.sleep(3)
    return f'异常：{last_e}'

# ---------- 主入口 ----------
def main():
    cookies = parse_env()
    msgs = []
    for idx, ck in enumerate(cookies, 1):
        print(f'===== 账号 {idx} =====')
        msg = sign_one(ck)
        print(msg)
        msgs.append(f'=====🙍 账号{idx} =====\n{msg} \n ==========')
        if idx != len(cookies):
            time.sleep(10)
    # 统一推送
    if msgs:
        push('飞牛签到', '\n\n'.join(msgs))
    print('全部完成')

if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        print('❌', e)
        push('❌ 飞牛签到异常', str(e))
        sys.exit(1)